<template>
  <md-main>
    <el-collapse-transition>
      <div class="md-body mb20" v-show="showSearch">
        <el-form :model="search" ref="search" size="small" :inline="true">
          <el-form-item label="标题" prop="title">
            <el-input v-model="search.title" class="w150" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="分类" prop="category">
            <md-dict-select :options="dictData['md_banner_category']" v-model="search.category" placeholder="请选择" class="w150"></md-dict-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <md-dict-select :options="dictData['sys_normal_disable']" v-model="search.status" placeholder="请选择" class="w150"></md-dict-select>
          </el-form-item>
          <el-form-item>
            <md-button type="primary" icon="el-icon-search" :prems="['web:banner:query']" @click="handleQuery()">搜索</md-button>
            <md-button icon="el-icon-refresh" @click="handleQueryReset()">重置</md-button>
          </el-form-item>
        </el-form>
      </div>
    </el-collapse-transition>

    <div class="md-body md-table">
      <md-toolbar>
        <md-button type="primary" size="small" plain :prems="['web:banner:add']" @click="handleAdd()">新增</md-button>
        <md-button type="success" size="small" plain :prems="['web:banner:del']" :disabled="tableSelectIds.length===0" @click="handleDelete()">批量删除</md-button>

        <template slot="right">
          <md-button size="mini" icon="el-icon-search" circle @click="showSearch=!showSearch"></md-button>
          <md-button type="primary" size="mini" icon="el-icon-refresh" circle @click="getTableDataList()"></md-button>
        </template>
      </md-toolbar>

      <el-table v-loading="tableLoading" :data="tableData" @selection-change="handleTableSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="bannerId" width="100" />
        <el-table-column label="轮播图" align="left" prop="picture" min-width="150">
          <template slot-scope="{ row }">
            <el-image style="width: 100%;" fit="cover" :src="row.picture" :preview-src-list="[row.picture]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="标题" align="left" prop="title" min-width="200" />
        <el-table-column label="链接地址" align="left" prop="url" width="200" show-overflow-tooltip>
          <template slot-scope="{row }">
            <el-link :href="row.url" type="primary" target="_blank">{{row.url}}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="分类" align="left" prop="category" width="100">
          <template slot-scope="{ row }">
            <md-dict-tag :options="dictData['md_banner_category']" :props="{ label: 'dictLabel', value: 'dictValue' }" :value="row.category" />
          </template>
        </el-table-column>
        <el-table-column label="排序" align="left" prop="sort" width="100" />
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template slot-scope="{ row }">
            <md-dict-tag :options="dictData['sys_normal_disable']" :props="{ label: 'dictLabel', value: 'dictValue' }" :value="row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
        <el-table-column label="操作" align="center" fixed="right" width="150">
          <template slot-scope="{ row }">
            <md-button size="mini" type="text" icon="el-icon-edit" :prems="['web:banner:update']" @click="handleUpdate(row)">修改</md-button>
            <md-button size="mini" type="text" icon="el-icon-delete" :prems="['web:banner:del']" @click="handleDelete(row)">删除</md-button>
          </template>
        </el-table-column>
      </el-table>

      <md-pagination v-show="tableTotal>0" :total="tableTotal" :page.sync="search.pageIndex" :limit.sync="search.pageSize" @pagination="getTableDataList" />
    </div>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="dialog.title" :visible.sync="dialog.open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="request" :rules="rules" size="small" label-width="100px" label-position="left">
        <el-form-item label="标题" prop="title">
          <el-input v-model="request.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="轮播图" prop="picture">
          <md-image-upload v-model="request.picture" label="上传图片"></md-image-upload>
        </el-form-item>
        <el-form-item label="链接地址" prop="url">
          <el-input v-model="request.url" placeholder="请输入链接地址" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <md-dict-select :options="dictData['md_banner_category']" v-model="request.category" placeholder="请选择"></md-dict-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input type="number" v-model="request.sort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <md-dict-radio-group :options="dictData['sys_normal_disable']" v-model="request.status"></md-dict-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="handleSubmit">确 定</el-button>
        <el-button size="small" @click="handleCancel">取 消</el-button>
      </div>
    </el-dialog>
  </md-main>
</template>

<script>
import { listPageBanner, insertBanner, updateBanner, delBanner, getBanner } from '@/api/web/banner.service.js'
import { mdGetDictData } from '@/ddd/dict.service.js'
export default {
  data () {
    return {
      // 显示隐藏查询条件
      showSearch: true,
      // 查询参数
      search: { ...searchParams },
      // 列表加载
      tableLoading: false,
      // 列表数据
      tableData: [],
      // 列表数据，总条数
      tableTotal: 0,
      // 已选择的列表数据
      tableSelectIds: [],
      // 添加/编辑请求参数
      request: requestParams,
      rules: rules,
      // 添加/编辑弹窗
      dialog: {
        title: '添加轮播题',
        open: false
      },
      dictData: {}
    }
  },
  mounted () {
    mdGetDictData(['sys_normal_disable', 'md_banner_category']).then(res => {
      this.dictData = res
    })
    this.getTableDataList()
  },
  methods: {
    /** 获取数据 */
    async getTableDataList () {
      this.tableLoading = true
      try {
        this.$http.post('/web/navigation/list', { status: '0' }).then()
        const res = await listPageBanner(this.search)

        this.tableData = res.data.items
        this.tableTotal = res.data.totalItems
      } catch (error) {
        console.log(error)
      }

      this.tableLoading = false
    },
    /** 表格复选框事件 */
    handleTableSelectionChange (event) {
      this.tableSelectIds = event.map(m => { return m.bannerId })
    },
    /** 搜索 */
    handleQuery () {
      this.search.pageNum = 1

      this.getTableDataList()
    },
    /** 重置搜索 */
    handleQueryReset () {
      this.search = { ...searchParams }

      this.getTableDataList()
    },
    // 重置表单数据
    handleReset () {
      this.request = { ...requestParams }
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },
    /** 删除 */
    async handleDelete (row) {
      try {
        const ids = row?.bannerId || this.tableSelectIds

        await this.$confirm(`是否确认删除编号为${ids}的数据项？`)

        await delBanner(ids)

        this.$message.success('删除成功')

        this.getTableDataList()
      } catch (error) {
        console.log(error)
      }
    },
    /** 添加 */
    async handleAdd () {
      try {
        this.handleReset()
        this.dialog.title = '添加轮播图'

        this.dialog.open = true

        this.request = { ...requestParams }
      } catch (error) {
        console.log(error)
      }
    },
    /** 修改 */
    async handleUpdate (row) {
      try {
        this.handleReset()
        const res = await getBanner(row.bannerId)

        this.request = res.data

        this.dialog.open = true

        this.dialog.title = '修改轮播图'

      } catch (error) {
        console.log(error)
      }
    },
    /** 提交 */
    handleSubmit () {
      this.$refs.form.validate(async valid => {
        if (!valid) {
          return
        }

        try {
          const params = Object.assign({}, { ...this.request })

          await (params.bannerId === undefined ? insertBanner : updateBanner)(params)

          this.$message.success(params.bannerId === undefined ? '添加成功' : '修改成功')

          this.dialog.open = false;

          this.getTableDataList()
        } catch (error) {
          console.log(error)
        }
      })
    },
    /** 取消 */
    handleCancel () {
      this.dialog.open = false

      this.handleReset()
    }
  }
}

const searchParams = {
  title: undefined,
  category: undefined,
  status: undefined,
  createBy: undefined,
  updateBy: undefined,
  beginDate: undefined,
  endDate: undefined,
  pageIndex: 1,
  pageSize: 10
}

const requestParams = {
  bannerId: undefined,
  title: undefined,
  picture: undefined,
  url: undefined,
  category: undefined,
  sort: 100,
  status: '0'
}

const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  picture: [{ required: true, message: '请上传图片', trigger: 'change' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
}
</script>